import ProDescriptions from '@ant-design/pro-descriptions';
import {useMount, useRequest} from 'ahooks';
import {Button, Card, Image, message, Modal, PageHeader, Popconfirm, Typography, Upload} from "antd";

import {useRef, useState} from "react";
import {auditWithdrawalInfo, getWithdrawalInfo, withdrawalStatus} from "@/services/ant-design-pro/log";
import {useLocation} from "umi";
import {getResult} from "@/services/ant-design-pro/attribute";
import {InboxOutlined, PlusOutlined, UploadOutlined} from "@ant-design/icons";
import {RcFile, UploadFile, UploadProps} from "antd/es/upload/interface";
import {UploadChangeParam} from "antd/es/upload";

import {ProFormText, ProFormTextArea, WaterMark} from '@ant-design/pro-components';
import {ProForm, ProFormInstance} from "@ant-design/pro-form";
import weishenhe from '@/assets/img/weishenhe.png';
import yishenhe from '@/assets/img/yishenhe.png';
import daishenhe from '@/assets/img/daishenhe.png';

const {Paragraph} = Typography;
const {Dragger} = Upload;
let pywtstatus = await getResult ( "paymentwithdrawalStatus", 0 );

const columns = [


  {
    title: '经销商',
    dataIndex: 'name',
    key: 'name',

  },
  {
    title: '提现金额',
    dataIndex: 'request_amount',
    valueType: 'money',
    key: 'request_amount',

  }, {
    title: '手续费',
    dataIndex: 'taxes',
    valueType: 'money',
    key: 'taxes',

  }, {
    title: '实际金额',
    dataIndex: 'amount',
    valueType: 'money',
    key: 'amount',

  }
  ,

  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    key: 'status',
    valueEnum: pywtstatus

  },

  {
    title: '收款人姓名',
    dataIndex: 'authName',
    valueType: 'authName',
    key: 'authName',

  }, {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',

  },
  {
    title: '申请时间',
    dataIndex: 'update_date',
    valueType: 'dateTime',

  }, {
    title: '发票编号',
    dataIndex: 'auditSn',
    //  valueType: 'dateTime',

  }, {
    title: '发票备注',
    dataIndex: 'auditRemark',
    //   valueType: 'dateTime',

  }
]

const columnsBankInfo = [
  {
    title: '提现方式',
    dataIndex: 'name',
    key: 'name',


  }, {
    title: '卡号',
    dataIndex: 'cardNo',
    key: 'cardNo',
  }, {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: "客户",
    dataIndex: "userName"
  },
  {
    title: "收款码",
    dataIndex: "image",
    valueType: "image"
  },
  {
    title: "地址",
    dataIndex: "address",
    valueType: "address"
  }
]

interface withdrawData {
  auditRemark: string;
  id: number;
  auditSn: string;
  auditImage: number;
  auditImageUrl: string;
}

//
const cloneTbale = () => {
  // @ts-ignore
  const {query} = useLocation ();
  const {
    run: fetchByInfo,
    refresh,
    data: dataInfo,
    loading,
  } = useRequest ( getWithdrawalInfo, {
    debounceWait: 100,
    manual: true, onSuccess(data) {
      let data1 = data?.data;
      setWDataInfo ( data1 )
      formRef.current?.setFieldsValue ( data1 )
    }
  } );
  const [wDataInfo, setWDataInfo] = useState<withdrawData> ( {
    auditImage: 0,
    id: 0,
    auditImageUrl: "",
    auditSn: "",
    auditRemark: ""
  } );

  useMount ( () => {
    // @ts-ignore

    fetchByInfo ( query?.id )

  } );
  const uploadButton = (
    <Button loading={loading} icon={<UploadOutlined/>}>
      发票上传
    </Button>
  );
  const beforeUpload = (file: RcFile) => {

    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error ( 'You can only upload JPG/PNG file!' );
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error ( 'Image must smaller than 2MB!' );
    }

    return isJpgOrPng && isLt2M;

  };
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log ( 'handleChange', info );

    if (info.file.status === 'uploading') {

      return;
    }
    if (info.file.status === 'done') {
      // @ts-ignore
      let data = info?.file?.response?.data;
      let p = {...wDataInfo, auditImage: data?.id, auditImageUrl: data?.url};
      setWDataInfo ( p )
      // Get this url from response in real world.
      // getBase64 ( info.file.originFileObj as RcFile, url => {
      //   setLoading ( false );
      //  setImageUrl ( url );
      //
      // } );
    }
  };
  const [isModalOpen, setIsModalOpen] = useState ( false );

  const showModal = () => {

    setIsModalOpen ( true );
  };
  const handleCancel = () => {
    setIsModalOpen ( false );
  };
  const formRef = useRef<ProFormInstance<withdrawData>> ();

  const getWorkImage = () => {
    let status = dataInfo?.data?.status;
    if (status == 1) {
      return yishenhe;
    }
    if (status == 3) {
      return weishenhe;
    }
    if (status == 2) {
      return daishenhe;
    }


  }
  const formatNumber = (n) => {
    n = n.toString ();
    return n[1] ? n : `0${n}`;
  };
  const formatTimeAll = (date: { getFullYear: () => any; getMonth: () => number; getDate: () => any; getHours: () => any; getMinutes: () => any; getSeconds: () => any; }) => {
    const year = date.getFullYear ();
    const month = date.getMonth () + 1;
    const day = date.getDate ();
    const hour = date.getHours ();
    const minute = date.getMinutes ();
    const second = date.getSeconds ();

    return (
      [year, month, day].map ( formatNumber ).join ( "-" ) +
      " " + [hour, minute, second].map ( formatNumber ).join ( ":" )
    );
  };

  const getCopyText = () => {
    let data = dataInfo?.data;
    // @ts-ignore
    let arr: [any] = []
    arr.push ( "姓名:" + data?.name )
    arr.push ( "订单号:" + data?.sn )
    arr.push ( "提现金额:" + data?.request_amount )
    arr.push ( "申请时间:" + formatTimeAll ( new Date ( data?.create_date ) ) )
    arr.push ( "提现方式:" + data?.bankInfo?.name )
    arr.push ( "卡号:" + data?.bankInfo?.cardNo )
    arr.push ( "手机号:" + data?.bankInfo.phone )
    arr.push ( "地址:" + data?.bankInfo.address )


    let s = arr.join ( ";\n\t\t" );
    return s;

  }

  const openFaPiaoModal = () => {

  }

  return (
    <WaterMark width={150} height={150} image={getWorkImage ()} fontColor={"#e20808"}>

      <Card
        title={
          <PageHeader
            className="site-page-header"
            onBack={() => window.history.back ()}
            title={<Paragraph copyable={{text: getCopyText ()}}>{dataInfo?.data?.authName}</Paragraph>}
            subTitle={dataInfo?.data?.sn}
            extra={
              <>
                <Button type="primary" onClick={showModal}>
                  <PlusOutlined/>
                  发票上传
                </Button>
                <Modal
                  visible={isModalOpen}
                  onCancel={handleCancel}
                  footer={false}
                  title="发票上传">
                  <ProForm<withdrawData>
                    formRef={formRef}

                    initialValues={wDataInfo}

                    onVisibleChange={() => {
                      setWDataInfo ( {...dataInfo?.data} )
                    }
                    }
                    submitTimeout={2000}
                    onFinish={(values) => {
                      setWDataInfo ( {...values} )
                      //   console.log ( wDataInfo );


                      return new Promise ( (resolve, reject) => {
                        auditWithdrawalInfo ( wDataInfo ).then ( res => {
                          if (res.success) {
                            resolve ( true )
                            handleCancel ();
                            message.success ( '提交成功' );
                            fetchByInfo ( wDataInfo?.id )
                          } else {
                            message.error ( '操作失败' );
                            reject ( false )

                          }
                        } ).catch ( e => {
                          message.error ( '操作失败' );

                          reject ( false )
                        } )
                      } )
                      //   return true;
                    }}
                  >
                    <ProFormText hidden={true} name="id" label="支付编号"/>
                    <Dragger
                      accept="jpg,png,jpeg"
                      name="file"
                      className="avatar-uploader"
                      showUploadList={false}
                      action={"/api/upload/image?type=10"}
                      beforeUpload={beforeUpload}
                      onChange={handleChange}
                    >
                      {wDataInfo?.auditImage > 0 ? <Image src={wDataInfo?.auditImageUrl}/> :
                        <p className="ant-upload-drag-icon">
                          <InboxOutlined/>
                        </p>}
                      <p>图片上传...</p>
                    </Dragger>
                    <ProFormText name="auditSn" label="支付编号"/>
                    <ProFormTextArea name="auditRemark" label="备注"/>
                  </ProForm>
                </Modal>


                {dataInfo?.data?.status == 2 ? <Popconfirm title={"通过确定吗！"} onConfirm={() => {
                  withdrawalStatus ( dataInfo?.data?.id, 1 ).then ( res => {
                    refresh ()
                  } )
                }}>
                  <Button type="primary">通过</Button> </Popconfirm> : ""}

                {dataInfo?.data?.status == 2 ? <Popconfirm title={"未通过确定吗！"} onConfirm={() => {
                  withdrawalStatus ( dataInfo?.data?.id, 3 ).then ( res => {
                    refresh ()
                  } )
                }}>
                  <Button type="primary" danger>未通过</Button> </Popconfirm> : ""}
              </>}
          />
        }
        bordered={false}
      ><ProDescriptions
        title="提现信息"
        dataSource={dataInfo?.data}
        columns={columns}
      />
        <ProDescriptions
          title="提现信息"
          dataSource={dataInfo?.data?.bankInfo}
          columns={columnsBankInfo}
        />
        <Image src={dataInfo?.data?.auditImageUrl}/>

      </Card>
    </WaterMark>);
};

export default cloneTbale;
